<template>
  <Header title="修改信息"></Header>
  <div class="modifyingUserData">
    <div class="modifyingUserData-content">
      <van-form @submit="onSubmit">
        <van-cell-group inset>
          <!-- 上传头像 -->
          <span class="avatarChange">头像更换</span>
          <div><van-uploader :after-read="afterRead" v-model="fileList" multiple :max-count="1" /></div>
          <van-field v-model="data.nickname" name="昵称" label="昵称" placeholder="昵称"
            :rules="[{ required: true, message: '请填写昵称' }]" />
          <van-field v-model="data.signature" name="签名" label="签名" placeholder="签名"
            :rules="[{ required: true, message: '请填签名' }]" />

          <van-field v-model="data.password1" type="password" name="原始密码" label="原始密码" placeholder="原始密码"
            :rules="[{ required: true, message: '请填写密码' }]" />

          <van-field v-model="data.password" type="password" name="新密码" label="新密码" placeholder="新密码"
            :rules="[{ required: true, message: '请填写密码' }]" />


        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">
            提交修改
          </van-button>
        </div>
      </van-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import Header from '@/components/Header.vue';
import { reactive } from 'vue';
import axios from '@/api/index.js'
import { showFailToast } from 'vant';

const route = useRoute()
const router = useRouter()



const value = ref([{ url: 'https://fastly.jsdelivr.net/npm/@vant/assets/leaf.jpeg' }]);

const data = reactive({
  username: route.query['username'],
  nickname: '',
  password: '',
  password1: '',
  fileList: '',
  signature: ''
})
console.log(route.query['username']);
const afterRead = (file) => {
  // 此时可以自行将文件上传至服务器
  console.log(file);
  data.fileList = file.content
};

const onSubmit = async () => {
  const password2 = await axios.post('/users/findPassword', {
    username: data.username
  })
  // console.log(data.password1);
  // console.log(password2.data[0].password);
  if (data.password1 === password2.data[0].password) {
    const result = await axios.post('/users/changeUserData', {
      nickname: data.nickname,
      password: data.password,
      username: data.username,
      avatar: data.fileList,
      signature: data.signature
    })
    router.push('/login')
    console.log(result);
  } else {
    showFailToast('原始密码错误')
  }
}

const fileList = ref([]);
</script>

<style lang="less" scoped>
.modifyingUserData {
  height: 100vh;
  width: 100vw;
  font-size: 24px;

  .avatarChange {
    font-size: 16px;
    padding-left: 16px;
  }

  .modifyingUserData-content {
    height: 10rem;
    margin: 2rem auto;

  }
}
</style>